package com.leyou.page.service;

import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String, Object> loadItemModel(Long spuId) {
        // TODO 先去redis取，如果有，则直接返回，没有才继续
        // 查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        // 查询分类
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        // 查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        // 查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecs(spu.getCid3());
        // 封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("categories", categories);
        map.put("brand", brand);
        map.put("spuName", spu.getName());
        map.put("subTitle", spu.getSubTitle());
        map.put("detail", spu.getSpuDetail());
        map.put("skus", spu.getSkus());
        map.put("specs", specs);

        // TODO 把map存入Redis中
        return map;
    }

    private static final String ITEM_BASE_DIR = "C:\\lesson\\heima74\\nginx-1.12.2\\html\\item";

    private static final ThreadPoolExecutor ex = new ThreadPoolExecutor(
            5,
            10,
            60,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10),
            new ThreadFactory() {
                int count = 0;
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "createItemHtmlTask-" + count++ );
                }
            });
    private static final ExecutorService es = Executors.newFixedThreadPool(10);

    public void asyncCreateItemHtml(Long spuId){
        es.submit(() -> createItemHtml(spuId));
    }

    public void createItemHtml(Long spuId) {
        // 准备上下文
        Context context = new Context();
        context.setVariables(loadItemModel(spuId));

        // 准备目标文件
        File file = new File(ITEM_BASE_DIR, spuId + ".html");

        // 准备输出流
        try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {

            // 渲染页面，并且写出到指定文件
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("生成静态页失败，商品id：【{}】, 原因：{}", spuId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void deleteItemHtml(Long spuId) {
        // 准备目标文件
        File file = new File(ITEM_BASE_DIR, spuId + ".html");
        // 删除
        if(file.exists()){
            boolean isDelete = file.delete();
            if(!isDelete){
                throw new RuntimeException("删除商品静态页失败！");
            }
        }
    }
}
